<!-- 组织-组织机构管理-组织机构页面 -->
<template>
  <a-modal
    width="80%"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    draggable
    title-align="center"
  >
    <template #title>
      <div>组织机构列表</div>
    </template>
    <div class="container">
      <div class="header">
        <div class="header-front">
          <a-space>
            <a-input-search
              v-model="nameSearch"
              placeholder="请输入组织名称"
              :style="{
                width: '220px'
              }"
              search-button
              @search="onSearch"
              @press-enter="onSearch"
            >
              <icon-search />
            </a-input-search>
          </a-space>
        </div>
      </div>
      <div class="main">
        <TableTurn
          :tableData="getTableData"
          :args="args"
          ref="tableRef"
          :isShowPagination="false"
        >
          <a-table-column
            :title="item.name"
            v-for="(item, index) in selectedHeader"
            :key="index"
            :data-index="item.code"
            :width="200"
            :sortable="{
              sortDirections: ['ascend', 'descend']
            }"
            :fixed="
              item.code === 'C30BBF36A5AF541F7A2657671DEE2EDD6' ? 'left' : ''
            "
          >
            <!-- 组织类型 -->
            <template
              v-if="item.code === 'C3D33FA57216F4968BDE51C31D623FC09'"
              #cell="{ record }"
            >
              <div>
                {{
                  organizationTypeList.find(
                    (item: any) =>
                      item.id == record['C3D33FA57216F4968BDE51C31D623FC09']
                  )?.name
                }}
              </div>
            </template>

            <!-- 上级组织 -->
            <template
              v-else-if="item.code === 'C073F4F41C46D4CA3AF3BEC1F51A8F410'"
              #cell="{ record }"
            >
              <div>
                {{
                  record['C073F4F41C46D4CA3AF3BEC1F51A8F410'] == 0
                    ? '无'
                    : deptList.find(
                        (item: any) =>
                          item.id == record['C073F4F41C46D4CA3AF3BEC1F51A8F410']
                      )['C30BBF36A5AF541F7A2657671DEE2EDD6']
                }}
              </div>
            </template>

            <!-- 上级组织编码 -->
            <template
              v-else-if="item.code === 'CBD9EC71A717B47E6A844F084E6035353'"
              #cell="{ record }"
            >
              <div>
                {{
                  record['C073F4F41C46D4CA3AF3BEC1F51A8F410'] == 0
                    ? '无'
                    : deptList.find(
                        (item: any) =>
                          item.id == record['C073F4F41C46D4CA3AF3BEC1F51A8F410']
                      )['CB1AAC9E508714223BA4D1596FE690877']
                }}
              </div>
            </template>

            <!-- 工作地点 -->
            <template
              v-else-if="item.code === 'CE009C2E2B542409D815F0D3D54FE0E2B'"
              #cell="{ record }"
            >
              {{
                workPlaceList.find(
                  (item: any) =>
                    item.id == record['CE009C2E2B542409D815F0D3D54FE0E2B']
                )?.name
              }}
            </template>

            <!-- 是否为独立法人 -->
            <template
              v-else-if="item.code === 'C37521ED1EF684F1F96B08FF8852E6030'"
              #cell="{ record }"
            >
              <div>
                {{
                  record['C37521ED1EF684F1F96B08FF8852E6030'] === 1
                    ? '是'
                    : '否'
                }}
              </div>
            </template>

            <!-- 是否为虚拟组织 -->
            <template
              v-else-if="item.code === 'C80DC4DFCBE0B4B2F83DA0C353E521691'"
              #cell="{ record }"
            >
              <div>
                {{
                  record['C80DC4DFCBE0B4B2F83DA0C353E521691'] === 1
                    ? '是'
                    : '否'
                }}
              </div>
            </template>

            <!-- 上级组织 -->
            <!-- <template
            v-else-if="item.code === 'C22648100'"
            #cell="{ record }"
          >
            {{
              organizationList.find(
                (item: any) => item.id == record['C22648100']
              )['C30BBF36A5AF541F7A2657671DEE2EDD6']
            }}
          </template> -->

            <!-- 组织负责人 -->
            <template
              v-else-if="item.code === 'CB0C63F38283045F58FFF1B1EABE5D151'"
              #cell="{ record }"
            >
              {{
                userList.find(
                  (item: any) =>
                    item.id == record['CB0C63F38283045F58FFF1B1EABE5D151']
                )?.name
              }}
            </template>

            <!-- 分管领导  -->
            <template
              v-else-if="item.code === 'CA6BD9CC1C99D4D13AD4F5009EF4F9586'"
              #cell="{ record }"
            >
              {{
                userList.find(
                  (item: any) =>
                    item.id == record['CA6BD9CC1C99D4D13AD4F5009EF4F9586']
                )?.name
              }}
            </template>
          </a-table-column>
          <a-table-column title="是否启用" :width="100" data-index="enable">
            <template #cell="{ record }">
              <span
                :style="{
                  color: record.enable === 1 ? '' : 'red'
                }"
              >
                {{ record.enable === 1 ? '是' : '否' }}
              </span>
            </template>
          </a-table-column>
        </TableTurn>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { flatTree, dataTreeFilter, downloadExcelFile } from '@/utils/utils';
import {
  GetOrganizationList,
  GetWorkPlaceList
} from '@/apis/management/organization/organizationManagement';
import { OrganizationPatternSearch } from '@/apis/management/organization/baseSetting/organizationalType';
import { GetHeaderSetting } from '@/apis/management/base';
import { GetUserList } from '@/apis/management/user';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框，
    selectedIds: number[]; // 选中的ids
  }>(),
  {
    visible: false
  }
);
const emit = defineEmits(['update:visible', 'organizationEmit']);

let nameSearch = ref(''); //名称搜索框

let tableRef = ref(); // 储存table的ref
let flatData = ref<any>([]); // 储存扁平化的数据

let loading = ref(true);

/*
 判断弹出哪种弹出框
      1 移动组织
      2 合并
      3 启用
      4 停用
      5 删除
    */
let type = ref(0);

/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

watch(
  () => props.visible,
  (newVal: any) => {
    if (newVal) {
      tableRef.value.selectedList = props.selectedIds;
    }
  }
);

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});
let expandTreeArr: any = [];

const formatData = (tree: any) => {
  if (tree.children && tree.children.length > 0) {
    tree.children.forEach((item: any, index: number) => {
      if (item.children && item.children.length > 0) {
        formatData(item);
        item.hasChildren = true;
      } else {
        item.hasChildren = false;
      }
      expandTreeArr[item.id] = item;
    });
  }
};

let organizationList = ref();

// 模糊搜索过滤函数
const maptree = (treeData: any, val: string) => {
  let newarr: any = [];
  treeData.forEach((ele: any) => {
    // 如果是组织名称C30BBF36A5AF541F7A2657671DEE2EDD6
    if (ele['C30BBF36A5AF541F7A2657671DEE2EDD6'].indexOf(val) > -1)
      newarr.push(ele);
    else {
      if (ele.children && ele.children.length > 0) {
        let redata = maptree(ele.children, val);
        if (redata && redata.length > 0) {
          let obj = {
            ...ele,
            children: redata
          };
          newarr.push(obj);
        }
      }
    }
  });
  return newarr;
};

let deptList: any = ref([]);
// 获取表格数据
const getTableData = async () => {
  try {
    const res = await GetOrganizationList({});
    loading.value = false;
    flatData.value = flatTree(res);
    // organizationList.value = dataTreeFilter(res);
    organizationList.value = maptree(dataTreeFilter(res), nameSearch.value);
    deptList.value = flatTree(dataTreeFilter(res));
    // 默认展开所有行
    flatData.value.forEach((item: any) => {
      tableRef.value.currExpandedKeys.push(item.id);
    });
    // flatData.value = flatTree(res, true);
    console.log('====================================ZXC');
    console.log(organizationList.value);
    console.log(flatData.value);
    console.log(deptList.value);

    console.log('====================================');
    // formatData(res[0]);
    return Promise.resolve(organizationList.value);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 搜索数据
const onSearch = async () => {
  tableRef.value.loadData();
};

let headerSetting = ref<any>([]); // 当前的表头数据
let organizationTypeList = ref<any>([]); // 组织类型数据
let workPlaceList = ref<any>([]); // 工作地点数据
let userList = ref<any>([]); // 人员列表数据

/*
  获取数据
  分别为
    表头数据
    组织类型列表
    工作地点
    人员列表
*/
const getData = async () => {
  try {
    const res: any = await Promise.all([
      GetHeaderSetting({
        type: 1,
        userId: +(localStorage.getItem('userId') as string)
      }),
      OrganizationPatternSearch({
        page: 1,
        size: -1
      }),
      GetWorkPlaceList({
        page: 1,
        size: -1
      }),
      GetUserList({
        page: 1,
        size: -1
      })
      // GetOrganizationListDetail({
      //   id: 1
      // })
    ]);
    headerSetting.value = res[0].header;
    organizationTypeList.value = res[1].content;
    workPlaceList.value = res[2].content;
    userList.value = res[3].content;
    console.log('resresresres', headerSetting.value);
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();
// 在表格上显示的表头
const selectedHeader = computed(() => {
  let arr: any = [];
  headerSetting.value.forEach((item1: any) => {
    arr = [
      ...arr,
      ...item1.heads.filter((item2: any) => item2.isDefault === true)
    ];
  });
  arr.sort((a: any, b: any) => a.sort - b.sort);
  return arr;
});

// 保存
const handleOk = () => {
  const temp = flatTree(dataTreeFilter(deptList.value)).filter((item: any) =>
    selectedList.value.includes(item.id)
  );
  emit('organizationEmit', selectedList.value, temp);
  // 清空选择器
  // tableRef.value.selectedListData = [];
  tableRef.value.selectedList = [];
  emit('update:visible', false);
};

// 取消
const handleCancel = () => {
  // 清空选择器
  // tableRef.value.selectedListData = [];
  tableRef.value.selectedList = [];
  emit('update:visible', false);
};
</script>

<style lang="less" scoped>
.container {
  padding: 10px 20px;
  .header {
    display: flex;
    justify-content: space-between;
    &-front {
      position: relative;
      line-height: 30px;
    }
    .commonBtns {
      background-color: rgb(var(--primary-1));
    }
  }
  .main {
    margin-top: 20px;
  }
}
</style>
